 
 import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { prisma } from '@/lib/db';

// GET /api/projects/[id]/stats - 获取项目统计数据
export async function GET(
  request: NextRequest,
  context: { params: { id: string } }
) {
  try {
    const params = context.params;
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const projectId = params.id;

    // 检查用户是否有权限访问该项目
    const projectAccess = await prisma.projectUser.findUnique({
      where: {
        userId_projectId: {
          userId,
          projectId,
        },
      },
    });

    if (!projectAccess) {
      return NextResponse.json({ error: '无权访问此项目' }, { status: 403 });
    }

    // 查询项目基本信息
    const project = await prisma.project.findUnique({
      where: { id: projectId },
      include: {
        tasks: true,
        users: {
          include: {
            user: true,
          }
        },
        activities: {
          orderBy: { createdAt: 'desc' },
          take: 100
        }
      }
    });

    if (!project) {
      return NextResponse.json({ error: '项目不存在' }, { status: 404 });
    }

    // 计算任务状态统计
    const tasks = project.tasks;
    const tasksByStatus = {
      todo: tasks.filter(task => task.status === 'TODO').length,
      inProgress: tasks.filter(task => task.status === 'IN_PROGRESS').length,
      review: tasks.filter(task => task.status === 'REVIEW').length,
      done: tasks.filter(task => task.status === 'DONE').length
    };

    // 计算总任务数和已完成任务数
    const totalTasks = tasks.length;
    const completedTasks = tasks.filter(task => task.status === 'DONE').length;

    // 计算团队成员统计
    const memberStats = await Promise.all(project.users.map(async (projectUser) => {
      const userActivities = await prisma.activity.count({
        where: {
          userId: projectUser.userId,
          projectId
        }
      });

      const userCompletedTasks = await prisma.task.count({
        where: {
          assigneeId: projectUser.userId,
          projectId,
          status: 'DONE'
        }
      });

      const userLastActive = await prisma.activity.findFirst({
        where: {
          userId: projectUser.userId,
          projectId
        },
        orderBy: {
          createdAt: 'desc'
        },
        select: {
          createdAt: true
        }
      });

      return {
        member: projectUser.user,
        activity: userActivities,
        completedTasks: userCompletedTasks,
        lastActive: userLastActive?.createdAt || new Date()
      };
    }));

    // 计算时间趋势 (过去30天任务完成情况)
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const taskCompletionTrend = await prisma.task.findMany({
      where: {
        projectId,
        status: 'DONE',
        updatedAt: {
          gte: thirtyDaysAgo
        }
      },
      select: {
        updatedAt: true
      },
      orderBy: {
        updatedAt: 'asc'
      }
    });

    // 按日期分组
    const tasksByDate = taskCompletionTrend.reduce((acc, task) => {
      const date = task.updatedAt.toISOString().split('T')[0];
      if (!acc[date]) {
        acc[date] = 0;
      }
      acc[date]++;
      return acc;
    }, {} as Record<string, number>);

    // 转换为数组格式
    const trends = {
      taskCompletion: Object.entries(tasksByDate).map(([date, count]) => ({
        date,
        count
      }))
    };

    // 计算预估工时 (假设每个任务平均需要2小时)
    const estimatedHours = totalTasks * 2;
    const actualHours = completedTasks * 2;
    const remainingHours = (totalTasks - completedTasks) * 2;

    // 构造返回数据
    const stats = {
      projectName: project.name,
      overview: {
        totalTasks,
        completedTasks,
        estimatedHours,
        actualHours,
        remainingHours
      },
      tasksByStatus,
      memberStats,
      trends
    };

    return NextResponse.json(stats);
  } catch (error) {
    console.error('获取项目统计数据失败:', error);
    return NextResponse.json(
      { error: '获取项目统计数据失败' },
      { status: 500 }
    );
  }
}
